package fun.coding.leetcode;

public class LengthOfLastWord {

	public static void main(String[] args) {

	}

    public int lengthOfLastWord(String s) {
    	if (s == null || s.length() == 0) return 0;
    	
    	int length = 0;
    	boolean isInWord = false;
    	for (int i = s.length() - 1; i >= 0; i--) {
    		while (i >= 0 && s.charAt(i) == ' ') i--;
    		
    		isInWord = true;
    		
    		while (i >= 0 && s.charAt(i) != ' ') {
    			length++;
    			i--;
    		}
    		
    		if (isInWord) break;
    	}
    	
    	return length;
    }
	
	// Using split is like cheating, the goal here is only scan the string once
    public int lengthOfLastWordCheating(String s) {
        if (s == null || s.isEmpty()) {
        	return 0;
        }

        s = s.trim();
    	String[] ss = s.split(" ");
    	return ss.length == 0 ? 0 : ss[ss.length - 1].length();
    }
    
}
